package com.ruoyi.zhifubao.service.impl;


import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import com.ruoyi.zhifubao.domain.AlipayUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;


/**
 * @program: ruoyi
 * @description: 支付宝第三方登录
 * @author: yanghua
 * @create: 2020-09-30 11:34
 **/
@Service
public class AlipayLoginService implements InitializingBean {
    private static final Logger LOGGER = LoggerFactory.getLogger(AlipayLoginService.class);

    /**
     * Alipay客户端
     */
    private AlipayClient alipayClient;

    /**
     * 支付宝网关
     */
    private static final String ALIPAY_BORDER_DEV = "https://openapi.alipaydev.com/gateway.do";
    private static final String ALIPAY_BORDER_PROD = "https://openapi.alipay.com/gateway.do";
    /**
     * appID
     **/
    private static final String APP_ID_DEV = "2021000116674174";
    private static final String APP_ID_PROD = "xxxxxx";
    /**
     * 私钥
     */
    public static String APP_PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDRMu8kN7oogZ/uhmPnY6qLD91DfJBwP8iBlFaYVUzvNrM7CQqcWzUgdx2asgz7KzsinKfWbcpji5QVCaKoKRq8yJE16ZDKGnAvcgxT/GRbMnGZGfbIG0DrmFcvaSWwEpKvSvDpt/z5VkbfrSzIqleLx9K5FwhS4PZevUMX0BQuDM8nL/azVvDkqw5Ta8ZmI/4dOm3O6Qo9awJiWodp9G6Xp60+bZe7hdiZQgq0sIbA9Iy4J1PneHKcJk46GY6CxtQla2u6T4Km3+y1k9ismHFdI9kc3BtX0KnvFM01n9hSeliu+di+qm3d8IpI99KqevklLwS63omNxGXJlEiWdK3lAgMBAAECggEAawvUIMU/RcDmlIhCEMIIH3ZzszfHNR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7oOzd/F7Z5bwxHeVSrBO61bSmO5BohhIg7+GXfvtY+zA4rz9/LTzDEwTT31eGwE8mbapK9BzxGE+AsCHQ4EqbNY5/GUluLwq1F01OlK39S";
    /**
     * 公钥
     */
    public static String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjvpst2qG+CDLC93Nu10DTfWKcUiodc6ZvToTva+GsBSVVmBTna3T/2moD4NSGqiAVHc59NVphupPYTC0O17z0zvUK03QLHE+LWci81qQYDzpjI23Xz+h/DpKfO07vvOmGVXZt7blPAtLqfoBBc5PKiYDtwLeHy+0qmBKpEKszAjFQWyEnqaEyWenUK18ImIL+P/HyqyP8OOhE8mOJlSH0ZjMpBGwP7PQy+HEtWhlo7CUKtDOIDj1lrOCB0wdr0ToNv4lYUCX9tsImH8vHrIHGvLH+iulVa4/eFNuD6l/6R1QpCeYIAG9cGNk+8nN8jzhhy6tiJdcdeY/2fC/ng5/pwIDAQAB";

    @Override
    public void afterPropertiesSet() throws Exception {
        alipayClient = new DefaultAlipayClient(ALIPAY_BORDER_DEV, APP_ID_DEV, APP_PRIVATE_KEY, "json", "UTF-8", ALIPAY_PUBLIC_KEY, "RSA2");
    }

    /**
     * 根据auth_code获取用户的user_id和access_token
     *
     * @param authCode
     * @return
     */
    public String getAccessToken(String authCode) {
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        request.setCode(authCode);
        request.setGrantType("authorization_code");
        try {
            AlipaySystemOauthTokenResponse oauthTokenResponse = alipayClient.execute(request);
            return oauthTokenResponse.getAccessToken();
        } catch (Exception e) {

            LOGGER.error("使用authCode获取信息失败！", e);
            return null;
        }
    }

    /**
     * 根据access_token获取用户信息（这只是做了一半了，还需要补充上自己的业务逻辑）
     *
     * @param token
     * @return
     */
    public AlipayUser getUserInfoByToken(String token) {
        AlipayUserInfoShareRequest request = new AlipayUserInfoShareRequest();
        try {
            AlipayUserInfoShareResponse response = alipayClient.execute(request, token);
            if (response.isSuccess()) {
                //打印响应信息
//                System.out.println(ReflectionToStringBuilder.toString(response));
                //封装支付宝对象信息
                AlipayUser alipayUser = new AlipayUser();
                alipayUser.setUuid(response.getUserId());
                alipayUser.setAddress(response.getAddress());
                alipayUser.setCertNo(response.getCertNo());
                alipayUser.setCity(response.getCity());
                alipayUser.setCollegeName(response.getCollegeName());
                alipayUser.setDegree(response.getDegree());
                alipayUser.setMobile(response.getMobile());
                alipayUser.setPhone(response.getPhone());
                alipayUser.setProvince(response.getProvince());
                alipayUser.setUserName(response.getUserName());
                alipayUser.setNickName(response.getNickName());
                //
                return alipayUser;
            }
            LOGGER.error("根据 access_token获取用户信息失败!");
            return null;

        } catch (Exception e) {
            LOGGER.error("根据 access_token获取用户信息抛出异常！", e);
            return null;
        }
    }
}
